﻿using System;
using System.Collections.Generic;

namespace Codeflows.Tracking
{
    public class CodeflowAction
    {
        public CodeflowAction(string name) : this(name, new Dictionary<string, object>())
        {
        }

        public CodeflowAction(string name, IDictionary<string, object> arguments)
            : this(name, arguments, 0, DateTime.UtcNow)
        {
        }

        public CodeflowAction(string name, IDictionary<string, object> arguments, int dispatchAttemptsCount,
                              DateTime startedAtUtc)
        {
            if (arguments == null) throw new ArgumentNullException("arguments");
            if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("A valid name is requied.");
            
            Name = name;
            Arguments = arguments;
            DispatchAttemptsCount = dispatchAttemptsCount;
            StartedAtUtc = startedAtUtc;
            IsCurrent = true;
        }

        public string Name { get; private set; }
        public int DispatchAttemptsCount { get; internal set; }
        public DateTime StartedAtUtc { get; private set; }
        public DateTime? CompletedAtUtc { get; private set; }
        public CodeflowStatus Result { get; private set; }
        public bool IsCurrent { get; private set; }
        public string ExceptionData { get; private set; }

        public IDictionary<string, object> Arguments { get; private set; }

        public void Complete(CodeflowStatus status)
        {
            CompletedAtUtc = DateTime.UtcNow;
            Result = status;
            IsCurrent = false;
        }

        public void Fault(CodeflowStatus status, Exception exception)
        {
            Complete(status);
            ExceptionData = exception.ToString();
        }
    }
}